package com.grechur.wanandroidcompose.viewmodel

import android.app.Application
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.grechur.wanandroidcompose.bean.article.Article
import com.grechur.wanandroidcompose.bean.article.ArticlesBean
import com.grechur.wanandroidcompose.bean.article.PageData
import com.grechur.wanandroidcompose.bean.banner.BannerBean
import com.grechur.wanandroidcompose.bean.banner.BannerInfo
import com.grechur.wanandroidcompose.http.service.HomeService
import com.grechur.wanandroidcompose.http.NetworkRequest

class HomeViewModel(application: Application) : BaseViewModel(application) {
    var banners by mutableStateOf(Result.success(listOf<BannerInfo>()))
        private set

    var homeArticles by mutableStateOf(Result.success(listOf<Article>()))
        private set
    var currentPageIndex by mutableStateOf(-1)
        private set
    var isOver by mutableStateOf(false)
        private set

    var isRefresh by mutableStateOf(false)

    suspend fun getNetBanners() {
        banners = try {
            val bannerBean = NetworkRequest.getService(getApplication(), HomeService::class.java).getBanner()
            val result = bannerBean.takeIf { it != null }?.let { bannerBe: BannerBean ->
                if (bannerBe.errorCode == 0) {
                    bannerBe.data.takeIf { !it.isNullOrEmpty() }?.let { bannerInfos: List<BannerInfo> ->
                        Result.success(bannerInfos)
                    }?:Result.success(listOf())
                } else {
                    Result.failure(IllegalArgumentException("error code ${bannerBe.errorCode} msg ${bannerBe.errorMsg}"))
                }
            }?: Result.failure(IllegalArgumentException(""))
            result
        } catch (e:Exception) {
            Result.failure(e)
        }

    }

    suspend fun getHomeArticles(pageIndex: Int = 0) {
        Log.e("zhouzhu","refresh:${isRefresh}")
        try {
            if (isRefresh) {
                isOver = false
            }
            if (!isOver) {
                val homeArticle = NetworkRequest.getService(getApplication(), HomeService::class.java).getHomeArticle(pageIndex)
                val result = homeArticle.takeIf { it != null }?.let {articlesBean: ArticlesBean ->
                    if (articlesBean.errorCode == 0) {
                        articlesBean.data.takeIf { it != null }?.let { data: PageData ->
                            isOver = data.over?:false
                            data.datas.takeIf { !it.isNullOrEmpty() }?.let { articles ->
                                currentPageIndex = pageIndex
                                if (isRefresh) {
                                    Result.success(articles)
                                } else {
                                    val old = homeArticles.getOrDefault(listOf())
                                    val all = old.toMutableList()
                                    all.addAll(articles)
                                    Result.success(all.toList())
                                }
                            }?:Result.success(homeArticles.getOrDefault(listOf()))
                        }?:Result.success(homeArticles.getOrDefault(listOf()))
                    } else {
                        Result.failure(IllegalArgumentException("error code ${articlesBean.errorCode} msg ${articlesBean.errorMsg}"))
                    }
                }?:Result.failure(IllegalArgumentException("网络请求失败"))
                isRefresh = false
                homeArticles = result
            }

        } catch (e : Exception) {
            isRefresh = false
            homeArticles = Result.failure(e)
        }

    }

    suspend fun refresh() {
        Log.e("zhouzhu","refresh")
        isRefresh = true
        currentPageIndex = -1
        getNetBanners()
        getHomeArticles(0)
    }

    override fun upItemData(index:Int,isAdd:Boolean) {
        Log.e("zhouzhu","upItemData index:${index} isAdd:${isAdd}")
        val list = homeArticles.getOrDefault(listOf())
        if (index >= 0 && index < list.size) {
//            Log.e("zhouzhu","upItemData before articles:${list.size}")
            val mutableListOf = list.toMutableList()
//            Log.e("zhouzhu","upItemData before mutableListOf:${mutableListOf.size}")
            val article = mutableListOf.removeAt(index).copy()
            article.collect = isAdd
            mutableListOf.add(index, article)
//            Log.e("zhouzhu","upItemData after articles:${mutableListOf.size}")
            homeArticles = Result.success(mutableListOf.toList())
        }
    }
}